package com.xingkeduo.gateway.authority.pojo;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xingkeduo.util.pojo.base.BaseJson;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.InputParamException;

/**
 * 身份验证实体类
 * 
 * @author GJ
 * @time 2019年3月18日 下午8:22:05
 * @description
 */
public class TokenJto extends BaseJson {
	public static Token createForNew(String json) throws Throwable {
		JsonNode root = validJson(json);
		if (root == null)
			throw new InputParamException(InputParamException.Type.INVALID, "参数");

		Token table = new Token();
		table.setUid(String.valueOf(validId(root, YesNoEnum.YES)));
		return table;
	}

	public static Token createForValid(String json) throws Throwable {
		JsonNode root = validJson(json);
		if (root == null)
			throw new InputParamException(InputParamException.Type.INVALID, "参数");

		Token table = new Token();
		table.setAccessToken(validAccessToken(root, YesNoEnum.YES));
		return table;
	}

	public static ObjectNode toJsonForSingle(Token table) throws Throwable {
		ObjectNode root = MAPPER.createObjectNode();

		if (table != null) {
			root.put("uid", table.getUid());
			root.put("accessToken", table.getAccessToken());
		}

		return root;
	}

	public static ObjectNode toJsonForPair(Token table) throws Throwable {
		ObjectNode root = MAPPER.createObjectNode();

		if (table != null) {
			root.put("uid", table.getUid());
			root.put("refreshToken", table.getRefreshToken());
			root.put("accessToken", table.getAccessToken());
		}

		return root;
	}

	public static String validAccessToken(JsonNode node, YesNoEnum isRequired) throws Throwable {
		return validString(node, "accesstoken", 200, isRequired);
	}
}
